<template>
  <view :class="theme">
    <uv-sticky :bg-color="$config.COLOR_TEXT_INVERSE">
      <uv-tabs @change="changeTabs" v-bind="{
        style: { padding: `20rpx 0` },
        list: orders,
        keyName: 'title',
        height: 36,
        scrollable: false,
        current: tabCurrent,
        bgColor: $config.COLOR_TEXT_INVERSE,
        fontSize: 28,
        activeStyle: { color: $config.COLOR_WHITE, fontWeight: 700 },
        inactiveStyle: { color: $config.COLOR_PLACEHOLDER },
        itemStyle: { fontSize: `28rpx`, padding: `12rpx` },
        lineColor: $config.COLOR_PRIMARY,
        lineHeight: 4,
        lineWidth: 60
      }" />
    </uv-sticky>

    <view class="m-24 b-rounded-16 bg-section">
      <view v-for="(order, orderIndex) in orders[tabCurrent].list" :key="order.id"
        :style="{ borderTop: orderIndex ? `2px dashed rgba(151,151,151,0.1)` : 'none' }" class="b-rounded-20 p-30">
        <view class="flex-row justify-between items-center">
          <text>订单号: {{ order.order_sn }}</text>
          <text>{{ order.status_text || "-" }}</text>
          <view class="flex-row" v-if="mapStatus[order.status]">
            <button @click="operation(item.key, orderIndex)" v-for="(item, index) in mapStatus[order.status]?.btn"
              :key="index" class="ml-20 items-center justify-center h-50 b-rounded-50 text-24 fw-500 !border-none color-base"
              plain hover-class="op-60"
              :style="item.type ? { backgroundColor: $config.COLOR_PRIMARY, color: $config.COLOR_BACKGROUND } : { border: `2rpx solid ${$config.COLOR_PLACEHOLDER}`, color: $config.COLOR_PLACEHOLDER }">
              {{ item.text }}
            </button>
          </view>
        </view>

        <view @click.stop="uniNavigator({ url: `/pages/client/mine/orderInfo?id=${order.id}` })"
          v-for="item in order.order_goods" :key="item.og_id" class="mt-22 flex-row">
          <uv-image :bg-color="$config.COLOR_TEXT" radius="16" width="200" height="200" :src="include(item.goods_image)" />
          <view class="flex-1 overflow-hidden ml-18 justify-around">
            <text class="multi-ellipsis text-28">{{ item.goods_name || "-" }}</text>
            <label class="items-baseline justify-between">
              <text class="color-16">
                数量: {{ item.num || 0 }}
              </text>
            </label>
          </view>
        </view>
      </view>
    </view>
    <view class="mt-30 mb-30 items-center">
      <uv-image v-if="!orders[tabCurrent].list.length" :showLoading="false" width="350" height="210" class="mt-60 mb-30"
        src="/static/img/blank.png" mode="aspectFit" />
      <uv-load-more :status="orders[tabCurrent].cache.status" :is-dot="!!orders[tabCurrent].list.length" />
    </view>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { pager, uniNavigator } from "@/common/libs/utils";
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};

const orders = reactive([
  {
    title: "全部",
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: null,
    next: false,
  },
  {
    title: "待发货",
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 0,
    next: false,
  },
  {
    title: "待收货",
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 1,
    next: false,
  },
  {
    title: "已完成",
    page: 0,
    limit: 20,
    list: [] as any[],
    cache: {
      page: 1,
      list: [] as any[],
      status: "nomore"
    },
    status: 2,
    next: false,
  },
]);

const mapStatus: AnyObject = {
  2: {
    text: "待收货",
    btn: [
      { text: "确认收货", type: 1, key: "receive" },
    ]
  }
};

const tabCurrent = ref(0);

onPullDownRefresh(() => {
  initOrders();
  setTimeout(uni.stopPullDownRefresh, 360);
});

const initOrders = () => {
  const item = orders[tabCurrent.value];
  item.page = 0;
  item.list = [];
  item.cache = {
    page: 1,
    list: [],
    status: "nomore"
  };
  item.next = false;
  getOrders();
}

const changeTabs = ({ index }: AnyObject) => {
  if (index === tabCurrent.value) return;
  if (orders[tabCurrent.value].cache.status === "loading") return;
  tabCurrent.value = index;
  uni.pageScrollTo({ scrollTop: 0 });
  initOrders();
}

onLoad(({ type }: any) => {
  type && (tabCurrent.value = +type);
});

onShow(() => initOrders());

onReachBottom(() => getOrders());

onPullDownRefresh(() => {
  initOrders();
  setTimeout(uni.stopPullDownRefresh, 360)
})

const getOrders = () => {
  const item = orders[tabCurrent.value];
  pager({ url: "/shopOrderLists", data: { status: item.status } }, item);
}

const operation = (key: string, index: number) => {
  const orderInfo = orders[tabCurrent.value].list[index];

  switch (key) {
    case "pay":
      uni.setStorage({
        key: "payInfo",
        data: {
          amount: Number(orderInfo.payment || 0).toFixed(2),
          description: "商品结算",
          order_type: 1,
          order_id: orderInfo.order_id
        },
        success() {
          uni.navigateTo({ url: "/pages/client/main/pay" });
        }
      });
      break;
    case "cancel":
      uni.showModal({
        title: "温馨提示",
        content: "确认要取消此订单吗？",
        success({ cancel }) {
          if (cancel) return;
          uni.request({
            url: "/cancelOrder",
            data: {
              order_id: orderInfo.order_id
            },
            success() {
              uni.showToast({ title: "已取消" });
              initOrders();
            }
          });
        }
      });
      break;
    case "receive":
      uni.showModal({
        title: "温馨提示",
        content: "确认已收到商品了吗？",
        success({ cancel }) {
          if (cancel) return;
          uni.request({
            url: "/confirmOrder",
            data: {
              order_id: orderInfo.order_id
            },
            success() {
              uni.showToast({ title: "已确认收货" });
              initOrders();
            }
          })
        }
      });
      break;
    default:
      break;
  }
}

</script>

<style lang="scss" scoped>
// scss
</style>